#! /bin/sh
#
# Copyright (c) Siemens AG, 2016
#
# Authors:
#  Jan Kiszka <jan.kiszka@siemens.com>
#
# derived from: Sysvinit is Copyright (C) 1991-2004 Miquel van Smoorenburg
#
# This work is licensed under the terms of the GNU GPL, version 2.  See
# the COPYING.GPLv2 file in the top-level directory.
#

### BEGIN INIT INFO
# Provides:          USB gadget device
# Required-Start:    $local_fs
# Should-Start:
# Required-Stop:     $local_fs
# Should-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Example initscript
# Description:       This file should be used to construct scripts to be
#                    placed in /etc/init.d
### END INIT INFO

PATH=/sbin:/usr/sbin:/bin:/usr/bin

DESC="ACM gadget device"
NAME="acm-gadget"

CONFIGFS="/sys/kernel/config"
DEVICE=$CONFIGFS/usb_gadget/$NAME

. /etc/init.d/functions || exit 1

#
# Function that starts the device
#
do_start() {
	mkdir -p $CONFIGFS
	mount -t configfs none $CONFIGFS

	mkdir $DEVICE
	echo 0x8086 > $DEVICE/idVendor
	echo 0xbabe > $DEVICE/idProduct

	mkdir -p $DEVICE/strings/0x409
	echo "Siemens AG" > $DEVICE/strings/0x409/manufacturer
	echo "IOT2000" > $DEVICE/strings/0x409/product

	mkdir -p $DEVICE/configs/serial.1
	mkdir -p $DEVICE/configs/serial.1/strings/0x409
	echo "CDC ACM config" > $DEVICE/configs/serial.1/strings/0x409/configuration

	mkdir -p $DEVICE/functions/acm.acm0
	ln -s $DEVICE/functions/acm.acm0 $DEVICE/configs/serial.1/

	echo 0000:00:14.2 > $DEVICE/UDC
}

#
# Function that stops the daemon/service
#
do_stop() {
	echo "Not supported." >&2
	exit 1

	rm $DEVICE/configs/serial.1/acm.acm0
	rmdir $DEVICE/functions/acm.acm0	# BUG?! This line hangs...
	rmdir $DEVICE/configs/serial.1/strings/0x409
	rmdir $DEVICE/configs/serial.1
	rmdir $DEVICE/strings/0x409
	rmdir $DEVICE

	return 0
}

#
# Function that shows if the gadget device is active
#
status_of_device () {
	if [ -d $DEVICE/configs/serial.1 ]; then
		echo "$DESC is configured."
		exit 0
	else
		echo "$DESC is not configured." >&2
		exit 1
	fi
}

case "$1" in
start)
	do_start
	;;
stop)
	do_stop || exit $?
	;;
status)
	status_of_device
	;;
restart)
	do_stop
	do_start
	;;
try-restart|force-reload)
	do_stop && do_start
	;;
*)
	echo "Usage: $0 {start|stop|status|restart|try-restart|force-reload}" >&2
	exit 3
	;;
esac
